import datetime
import functools
from coin.exchange.kr_rest.product.product_impl import generate_product_from_str2
from coin.base.datetime_util import to_timestamp_int
import coin.strategy.mm.tool.archive_base as abase


class AA(object):
  def __init__(self, products):
    self._products = products

  def on_book_reset(self, book_builder_name, book_builder):
    for product in self._products:
      book_builder.subscribe(product, functools.partial(self.on_book, product))
      if hasattr(book_builder, "subscribe_trade"):
        book_builder.subscribe_trade(product, functools.partial(self.on_trade, product))

  def on_book(self, product, book):
    print(
        ' book',
        datetime.datetime.fromtimestamp(book.timestamp / 1e9).strftime('%H:%M:%S') +
        ('%09d' % (book.timestamp % 1000000000)),
        'ask0(pq=',
        book.ask0(),
        '), bid0(pq=',
        book.bid0(),
        ')')

  def on_trade(self, product, trade):
    exchange = product.exchange
    print(
        'trade',
        datetime.datetime.fromtimestamp(trade.timestamp / 1e9).strftime('%H:%M:%S') + '.' +
        ('%09d' % (trade.timestamp % 1000000000)),
        '(p=',
        trade.price,
        ', q=',
        trade.qty,
        ')')


import datetime
from coin.strategy.mm.tool.archive_base import run_from_archive, symbols_to_products

start_time = datetime.datetime(2019, 12, 1, hour=0, minute=1)
end_time = datetime.datetime(2019, 12, 1, hour=0, minute=1, second=30)
products = [
    generate_product_from_str2(market_type='Futures',
                               exchange='Okex',
                               api_version='v3',
                               norm_product=symbol,
                               current_datetime=start_time) for symbol in ['BTC-USD.QUARTER']
]

feedsub_request = abase.products_to_feedsub_request_with_api_override(
    products, {'Futures:Okex': 'v3_realtime'}, "feed-01.ap-northeast-1.aws")
strategy = AA(products)

run_from_archive(feedsub_request,
                 strategy.on_book_reset,
                 start_time,
                 end_time,
                 machine=['feed-01.ap-northeast-1.aws'],
                 worker_id=1)
